import React, {FC, useCallback, useEffect, useMemo, useState} from "react";
import {Select} from "antd";
import {getLocale} from "../../../i18n/i18n.tsx";

interface SelectLevelProps {
    value: number,
    maxLevel: number,
    disabled: boolean,
    ds: any,
    onChange: Function
}

const SelectLevel: FC<SelectLevelProps> = (props) => {
    const [value, setValue] = useState<number>(0),
        [options, setOption] = useState<any[]>([]);

    const loadOptions: Function = useCallback(() => {
        const {maxLevel = 0}: { maxLevel: number } = props;
        let newOptions: any[] = [];
        for (let i: number = 0; i < maxLevel; i++) {
            newOptions.push({
                label: (i + 1) + getLocale("级", "Level"),
                value: (i + 1)
            });
        }
        newOptions.push({
            value: maxLevel,
            label: getLocale("全部", "All")
        });
        setOption(newOptions);
    }, [props.maxLevel]);

    const handelChange: Function = useCallback((value: any = "") => {
        setValue(value);
        props.onChange && props.onChange(value !== 0 ? value : "");
    }, [props.onChange]);

    useEffect(() => {
        loadOptions();
    }, [props.maxLevel]);

    useEffect(() => {
        const {ds = {}}: { ds?: any } = props;
        let newValue = ds.value || props.value;
        setValue(newValue);
    }, [props.ds]);

    const renderSelectLevel = useMemo(() => {
        const {disabled = false}: { disabled: boolean } = props;
        return (
            <Select
                {...props}
                value={value}
                style={{width: "100%"}}
                disabled={disabled}
                options={options}
                onChange={handelChange}
            />
        )
    }, [value, options]);

    return (renderSelectLevel);
};

export default React.memo(SelectLevel);